﻿#include "ssTextureMaterial.h"

namespace StarSeeker
{

ssTextureMaterial::ssTextureMaterial()
{
	m_pTexture = 0;
	m_shaderTexture.Init(1);
}

ssTextureMaterial::~ssTextureMaterial()
{
	if (m_pTexture)
	{
		SS_SAFE_DELETE(m_pTexture)
	}
}

ssTexture2D* ssTextureMaterial::SetTexture(ssTexture2D* pt)
{
	ssTexture2D* old = m_pTexture;
	m_pTexture = pt;
	BindTexture2DShaderUniform();
	return old;
}

void ssTextureMaterial::BindTexture2DShaderUniform()
{
	if (m_pTexture)
	{
		if (m_shaderTexture.Count() < m_pTexture->GetLayers())
		{
			m_shaderTexture.Resize(m_pTexture->GetLayers());
			m_shaderTexture.SetCount(m_pTexture->GetLayers());
		}
		ssString name(16);
		for (u8 i = 0; i < m_pTexture->GetLayers(); ++i)
		{
			name.Format("tex%d", i);
			m_shaderTexture[i].BindData(SS_GL_UNIFORM_TEX2D, name.GetString());
		}
	}
}

void ssTextureMaterial::OnRenderBegin()
{
	if (m_pTexture)
	{
		for (ulint i = 0; i < m_shaderTexture.Count(); ++i)
		{
			m_shaderTexture[i].Use(m_pShader, 0, i);
		}
		m_pTexture->Use();
	}
	SetShaderUniform();
}

void ssTextureMaterial::OnRenderEnd()
{
	if (m_pTexture)
	{
		m_pTexture->Nonuse();
	}
}

}
